/* eslint-disable */
window.CKEDITOR.plugins.add('autoformat', {
  onLoad:function(){
    CKEDITOR.document.appendStyleSheet(this.path + 'css/autoformat.css')
  },
  init: function (editor) {
    editor.on('beforeCommandExec', () => {
      editor.fire('unlockSnapshot') //解锁撤销快照记录
    })
    editor.on('afterCommandExec', evt => {
      if (evt.data.name === 'autoformat') {
        editor.fire('lockSnapshot') //锁定撤销快照记录
      }
    })
    editor.addCommand('autoformat', {
      exec: function (editor) {
        formatText(editor)
      }
    })
    editor.ui.addButton('AutoFormat', {
      label: '一键排版',
      command: 'autoformat'
    })
  }
})
//格式化
function formatText(editor) {
  let myeditor = editor
  /* 是否格式化字体样式 */
  let autoFormatFontStyle = editor.config.autoFormatFontStyle || false
  if (myeditor.mode == 'wysiwyg') {
    let tempimg = new Array()
    let temptable = new Array()
    let tempobject = new Array()
    let isPart = false //暂时无法实现局部格式化
    if (!isPart) {
      let tmpDiv = document.createElement('DIV')
      let editorhtml = myeditor.getData()
      editorhtml = editorhtml.replace(
        /<div style="page-break-after: always;?">\s*<span style="display: none;?">&nbsp;<\/span>\s*<\/div>/gi,
        '<p>[ page]</p>'
      ) //将div span标签替换为p 标签
      tmpDiv.innerHTML = editorhtml
        .replace(/&nbsp;/gi, '')
        .replace(/<div/gi, '<p')
        .replace(/<\/div/gi, '</p') //移除空格标签，div替换为p标签。

      if(autoFormatFontStyle){
        /* 字体样式做格式化统一 */
        if (window.navigator.userAgent.toLowerCase().indexOf('msie') > 0) {
          tmpDiv.innerHTML = tmpDiv.innerHTML.replace(/<\/p>/gi, '<br /></p>') //每个段落相隔一行
        } 
      } else {
        /* 字体样式不做格式化，只格式化段落 */
        const pNodes = tmpDiv.querySelectorAll('p')
        pNodes.forEach(item => {
          if(item.nodeName == 'P') {
            item.style.cssText = editor.config.formatStyle;
        }
        })
      }
      let tables = tmpDiv.getElementsByTagName('TABLE')
      if (tables != null && tables.length > 0) {
        for (let j = 0; j < tables.length; j++) {
          temptable[temptable.length] = tables[j].outerHTML
        }
        let formattableCount = 0
        for (let j = 0; j < tables.length; ) {
          tables[j].outerHTML = '#FormatTableID_' + formattableCount + '#'
          formattableCount++
        }
      }
      let objects = tmpDiv.getElementsByTagName('OBJECT')
      if (objects != null && objects.length > 0) {
        for (let j = 0; j < objects.length; j++) {
          tempobject[tempobject.length] = objects[j].outerHTML
        }
        let formatobjectCount = 0
        for (let j = 0; j < objects.length; ) {
          objects[j].outerHTML = '#FormatObjectID_' + formatobjectCount + '#'
          formatobjectCount++
        }
      }
      let imgs = tmpDiv.getElementsByTagName('IMG')
      if (imgs != null && imgs.length > 0) {
        for (let j = 0; j < imgs.length; j++) {
          let t = document.createElement('IMG')
          t.alt = imgs[j].alt
          t.src = imgs[j].src
          t.width = imgs[j].width
          t.height = imgs[j].height
          t.align = imgs[j].align
          tempimg[tempimg.length] = t
        }
        let formatImgCount = 0
        for (let j = 0; j < imgs.length; ) {
          imgs[j].outerHTML = '#FormatImgID_' + formatImgCount + '#'
          formatImgCount++
        }
      }
      // let strongarray = new Array()
      // let strongcount = 0
      // for (let i = 0; i < tmpDiv.getElementsByTagName('b').length; i++) {
      //   strongarray[strongcount] = tmpDiv
      //     .getElementsByTagName('b')
      //     [i].innerText.trim()
      //   tmpDiv.getElementsByTagName('b')[i].innerHTML =
      //     '#FormatStrongID_' + strongcount + '#'
      //   strongcount++
      // }
      // for (let i = 0; i < tmpDiv.getElementsByTagName('strong').length; i++) {
      //   strongarray[strongcount] = tmpDiv
      //     .getElementsByTagName('strong')
      //     [i].innerText.trim()
      //   tmpDiv.getElementsByTagName('strong')[i].innerHTML =
      //     '#FormatStrongID_' + strongcount + '#'
      //   strongcount++
      // }
      let html = ''
      if(autoFormatFontStyle){
        html = processFormatText(tmpDiv.innerText)
        html = html.replace(
          /<p>\[ page\]<\/p>/gi,
          '<div style="page-break-after: always;"><span style="display: none;">&nbsp;</span></div>'
        ) //p标签替换回原来的div和span标签。
      } else {
        html = tmpDiv.innerHTML.replace(
          /<p>\[ page\]<\/p>/gi,
          '<div style="page-break-after: always;"><span style="display: none;">&nbsp;</span></div>'
        ) //p标签替换回原来的div和span标签。
      }
      if (temptable != null && temptable.length > 0) {
        for (let j = 0; j < temptable.length; j++) {
          let tablehtml = temptable[j]
          html = html.replace('#FormatTableID_' + j + '#', tablehtml)
        }
      }
      if (tempobject != null && tempobject.length > 0) {
        for (let j = 0; j < tempobject.length; j++) {
          let objecthtml = '<p align="center">' + tempobject[j] + '</p>'
          html = html.replace('#FormatObjectID_' + j + '#', objecthtml)
        }
      }
      if (tempimg != null && tempimg.length > 0) {
        for (let j = 0; j < tempimg.length; j++) {
          let imgheight = ''
          let imgwidth = ''
          let imgalign = ''
          if (tempimg[j].height != 0)
            imgheight = ' height="' + tempimg[j].height + '"'
          if (tempimg[j].width != 0)
            imgwidth = ' width="' + tempimg[j].width + '"'
          if (tempimg[j].align != '')
            imgalign = ' align="' + tempimg[j].align + '"'
          let imghtml =
            '<p align="center"><img src="' +
            tempimg[j].src +
            '" alt="' +
            tempimg[j].alt +
            '"' +
            imgwidth +
            ' ' +
            imgheight +
            ' ' +
            imgalign +
            '" border="0"></p>'
          html = html.replace('#FormatImgID_' + j + '#', imghtml)
        }
      }
      // for (let i = 0; i < strongcount; i++) {
      //   html = html.replace(
      //     '#FormatStrongID_' + i + '#',
      //     '<p><strong>' + strongarray[i] + '</strong></p>'
      //   )
      // }
      while (html.indexOf('</p></p>') != -1)
        html = html.replace('</p></p>', '</p>')
      while (html.indexOf('<p><p align="center">') != -1)
        html = html.replace('<p><p align="center">', '<p align="center">')
      editor.setData(html)
    }
  } else {
    alert('必须在设计模式下操作！')
  }
}
function processFormatText(textContext) {
  let text = dbc2Sbc(textContext)
  // let prefix = ''
  let tmps = text.split('\n')
  let html = ''
  for (let i = 0; i < tmps.length; i++) {
    let tmp = tmps[i].trim()
    if (tmp.length > 0) {
      let reg = /#Format[A-Za-z]+_\d+#/gi
      let f = reg.exec(tmp)
      if (f != null) {
        tmp = tmp.replace(/#Format[A-Za-z]+_\d+#/gi, '')
        html += f
        if (tmp != '') html += '<p align="center">' + tmp + '</p>\n'
      } else {
        html += "<p>\&emsp;\&emsp;" + tmp + '</p>\n'
      }
    }
  }
  return html
}
function dbc2Sbc(str) {
  let result = ''
  for (let i = 0; i < str.length; i++) {
    let code = str.charCodeAt(i)
    // “65281”是“！”，“65373”是“｝”，“65292”是“，”。不转换"，"
    if (code >= 65281 && code < 65373 && code != 65292 && code != 65306) {
      // “65248”是转换码距
      result += String.fromCharCode(str.charCodeAt(i) - 65248)
    } else {
      result += str.charAt(i)
    }
  }
  return result
}
String.prototype.trim = function () {
  return this.replace(/(^[\s]*)|([\s]*$)/g, '')
}
String.prototype.leftTrim = function () {
  return this.replace(/(^\s*)/g, '')
}
String.prototype.rightTrim = function () {
  return this.replace(/(\s*$)/g, '')
}
